package config

import (
	"crypto/tls"
	"os"
	"shell/common"

	"github.com/go-playground/validator/v10"
	"github.com/google/uuid"
	"gopkg.in/yaml.v3"
)

type TcpPortsYaml struct {
	Enable bool   `yaml:"enable"`
	From   uint16 `yaml:"from" validate:"required_if=Enable true"`
	To     uint16 `yaml:"to" validate:"required_if=Enable true,gtefield=From"`
}

// 公网代理端配置
type ProxyConfigYaml struct {
	CaBase64   string        `yaml:"ca_base64" validate:"required,base64"`
	CertBase64 string        `yaml:"cert_base64" validate:"required,base64"`
	KeyBase64  string        `yaml:"key_base64" validate:"required,base64"`
	QuicPort   uint16        `yaml:"quic_port" validate:"required,gt=0"`
	TcpPorts   *TcpPortsYaml `yaml:"tcp_ports"`
	UUID       string        `yaml:"uuid" validate:"required,uuid"`
}

type ProxyConfig struct {
	TLSCfg   *tls.Config   // tls配置
	QuicPort uint16        // quic监听的端口
	TcpPorts *TcpPortsYaml // 开放的Tcp端口
	UUID     uuid.UUID     // 本节点uuid
}

// 解析配置文件，生成配置结构体
func ParseCfg(cfgPath string) (*ProxyConfig, error) {
	content, err := os.ReadFile(cfgPath)
	if err != nil {
		return nil, err
	}
	cfgYaml := new(ProxyConfigYaml)
	if err = yaml.Unmarshal(content, cfgYaml); err != nil {
		return nil, err
	}
	v := validator.New()
	if err = v.Struct(cfgYaml); err != nil {
		return nil, err
	}
	id, err := uuid.Parse(cfgYaml.UUID)
	if err != nil {
		return nil, err
	}
	tlsCfg, err := common.TlsCfg(cfgYaml.CaBase64, cfgYaml.CertBase64, cfgYaml.KeyBase64, true)
	if err != nil {
		return nil, err
	}
	result := new(ProxyConfig)
	result.TLSCfg = tlsCfg
	result.QuicPort = cfgYaml.QuicPort
	result.UUID = id
	if cfgYaml.TcpPorts != nil && cfgYaml.TcpPorts.Enable {
		result.TcpPorts = cfgYaml.TcpPorts
	} else {
		result.TcpPorts = nil
	}
	return result, nil
}
